extends RefCounted
class_name Controller

var _model: Model

var _previous_number: float = 0 :
	get:
		return _model.previous_number
	set(value):
		_model.previous_number = value
var _current_number : float = 0 :
	get:
		return _model.current_number
	set(value):
		_model.current_number = value
var _current_operator:String = "" :
	get:
		return _model.current_operator
	set(value):
		_model.current_operator = value
var _has_current_number : bool = false :
	get:
		return _model.has_current_number
	set(value):
		_model.has_current_number = value
# 添加此行以跟踪小数点后有多少数字
var _decimal_places: int = 0 :
	get:
		return _model.decimal_places 
	set(value):
		_model.decimal_places = value

signal display_changed

func _init(model) -> void:
	_model = model

func input_value(value: String) -> void:
	if value == "=":
		if _current_operator != "":
			_model.evaluate_expression()
	elif value in ["+", "-", "*", "/"]:
		# 如果已有一个运算符和两个数字，先完成运算
		if _current_operator != "":
			_model.evaluate_expression()
		_current_operator = value
		_previous_number = _current_number
		_current_number = 0
		_has_current_number = false
		_decimal_places = 0
	elif value == "C":
		_model.clear()
	elif value == ".":
		# 如果尚未输入小数点
		if _decimal_places == 0:
			_decimal_places = 1
			if not _has_current_number:
				_current_number = 0
				_has_current_number = true
	else:
		if _has_current_number:
			# 如果小数点被输入
			if _decimal_places > 0:
				_current_number += float(value) / pow(10, _decimal_places)
				_decimal_places += 1
			else:
				_current_number = _current_number * 10 + float(value)
		else:
			_current_number = float(value)
			_has_current_number = true
	display_changed.emit(get_display_value())

func get_display_value() -> String:
	var str_current_number : String = str(_current_number) if _decimal_places == 0 else "%.*f" % [_decimal_places - 1, _current_number]
		
	if _has_current_number and _decimal_places == 1 and "." not in str_current_number:
		str_current_number += "."
	if not _has_current_number:
		print("没有当前值")
		return str(_previous_number) + " " + str(_current_operator)
	elif _current_operator == "":
		print("只显示当前值")
		return str_current_number
	else:
		print("常规显示")
		return str(_previous_number) + " " + str(_current_operator) + " " + str_current_number
